const { success, failure } = require("../../utils/responses");
const usersService = require("../../services/mobile/usersService");
const jwt = require("jsonwebtoken");
const {
  NotFoundError,
  BadRequestError,
  UnauthorizedError,
} = require("../../utils/errors");
const moment = require("moment/moment");
const { Op } = require("sequelize");
const { User } = require("../../models");
const bcrypt = require("bcryptjs");

/**
 * 手机号模拟登录
 * @param req
 * @param res
 * @returns {Promise<void>}
 */
exports.phoneMocksLogin = async (req, res) => {
  try {
    const phone = req.body.phone;
    if (!phone) {
      throw new NotFoundError("手机号不能为空");
    }
    const user = await usersService.getUserByPhone(phone);
    if (!user) {
      throw new NotFoundError("用户不存在");
    }

    // 生成身份验证令牌
    const token = jwt.sign(
      {
        userId: user.id,
      },
      process.env.TOKEN_SECRET,
      { expiresIn: process.env.TOKEN_EXPIRES },
    );

    const data = {
      id: user.id,
      phone: user.phone,
      nickname: user.nickname,
      username: user.username,
      avatar: user.avatar,
      sex: user.sex,
      token: token,
    };
    success(res, "登录成功", data);
  } catch (error) {
    failure(res, error);
  }
};

/**
 * 微信登录
 * @param req
 * @param res
 * @returns {Promise<void>}
 */
exports.wechatLogin = async (req, res) => {
  failure(res, "暂未开放");
};

/**
 * 账号密码登录
 * @param req
 * @param res
 * @returns {Promise<void>}
 */
exports.accountAndPasswordLogin = async (req, res) => {
  const currentDate = moment();
  const futureDate = currentDate.add(30, "days");
  try {
    const { login, password } = req.body;
    if (!login) {
      throw new BadRequestError("邮箱/用户名必须填写.");
    }
    if (!password) {
      throw new BadRequestError("秘密必须填写.");
    }
    // 通过email 或 username,查询用户是否存在
    const user = await usersService.getUserByEmailOrUsername(login);
    if (!user) {
      throw new NotFoundError("用户不存在,无法登录.");
    }
    // 验证密码是否相等
    const isPasswordValid = bcrypt.compareSync(password, user.password);
    if (!isPasswordValid) {
      throw new UnauthorizedError("密码错误.");
    }
    // 生成身份验证令牌
    const token = jwt.sign(
      {
        userId: user.id,
      },
      process.env.TOKEN_SECRET,
      { expiresIn: process.env.TOKEN_EXPIRES },
    );

    const data = {
      id: user.id,
      phone: user.phone,
      nickname: user.nickname,
      username: user.username,
      avatar: user.avatar,
      sex: user.sex,
      token: token,
    };
    success(res, "登录成功", data);
  } catch (error) {
    failure(res, error);
  }
};

/**
 * 获取用户信息
 * @param req
 * @param res
 * @returns {Promise<void>}
 */
exports.getUserDetail = async (req, res) => {
  try {
    const id = req.query.id;
    if (!id) {
      throw new NotFoundError("用户ID为空");
    }
    const user = await usersService.getUserById(id);
    if (!user) {
      throw new NotFoundError("用户不存在");
    }

    const data = {
      id: user.id,
      phone: user.phone,
      nickname: user.nickname,
      username: user.username,
      avatar: user.avatar,
      sex: user.sex,
    };

    success(res, "获取用户信息成功", data);
  } catch (error) {
    failure(res, error);
  }
};
